﻿Imports SISSAT.Administration.DomainModels
Imports SISSAT.Administration.Services

Namespace Views
    Public Class WebUserDetailControlPresenter

        Private Property View As IWebUserDetailControlView
        Private Property Service As IUserService

        Public Sub New(view As IWebUserDetailControlView)
            Service = New UserService
            Me.View = view
            AddHandler Me.View.OnClear, AddressOf OnClear
            AddHandler Me.View.OnInitialization, AddressOf OnInitialization
            AddHandler Me.View.OnSubmit, AddressOf OnSubmit
        End Sub

        Private Sub OnInitialization()
            If Me.View.UserId = 0 Then
                Return
            End If

            Dim entity As SouthdaleUser = Service.ReadByUserId(Me.View.UserId)
            Me.View.OldPassword = entity.Password
            Me.View.Username = entity.Username
        End Sub

        Private Sub OnClear()
            Me.View.OldPassword = String.Empty
            Me.View.NewPassword = String.Empty
            Me.View.Username = String.Empty

            OnInitialization()
        End Sub

        Private Sub OnSubmit()
            If Me.View.UserId = 0 Then
                Service.Create(Me.View.EmployeeId, Me.View.Username, Me.View.OldPassword, Me.View.CurrentUserId)
            End If

            Dim entity As SouthdaleUser = Service.AuthenticateUser(Me.View.Username, Me.View.OldPassword)
            If entity Is Nothing Then
                OnClear()
                Throw New ArgumentNullException("Password is incorrect.")
            End If

            entity = Service.ReadByUserId(Me.View.UserId)
            entity.Password = Me.View.NewPassword
            entity.Username = Me.View.Username

            Service.Edit(entity, Me.View.CurrentUserId)
        End Sub

    End Class
End Namespace

